package com.ostms.adv.utils;

import android.annotation.SuppressLint;
import android.app.ActivityManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Environment;
import android.os.PowerManager;
import android.os.StatFs;
import android.support.v4.content.FileProvider;
import android.telephony.TelephonyManager;
import android.util.Log;

import com.ostms.adv.BuildConfig;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.Reader;
import java.lang.reflect.Method;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.URL;
import java.net.URLConnection;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.Enumeration;
import java.util.List;

import okhttp3.FormBody;
import okhttp3.MultipartBody;

public class Tools {
    private static final String TAG = Tools.class.getSimpleName();
    private static Bitmap pixel = null;

    public static boolean checkMemmery(Context context) {
        File file = Environment.getExternalStorageDirectory();
        StatFs statFs = new StatFs(file.getPath());
        long blockSizeLong = statFs.getBlockSizeLong();
        long blockCountLong = statFs.getBlockCountLong();
        long availableBlocksLong = statFs.getAvailableBlocksLong();
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        String num = df.format((float) availableBlocksLong / blockCountLong);
        LOG.i(TAG, "可用内存：" + num);
        if (Double.parseDouble(num) < 0.15) {
            return true;
        }
        return false;
    }

    public static String getMemmery(Context context) {
        File file = Environment.getExternalStorageDirectory();
        StatFs statFs = new StatFs(file.getPath());
        long blockCountLong = statFs.getBlockCountLong();
        long availableBlocksLong = statFs.getAvailableBlocksLong();
        DecimalFormat df = new DecimalFormat("0.00");//设置保留位数
        String num = df.format(((float) (blockCountLong - availableBlocksLong) / blockCountLong) * 100);
        LOG.i(TAG, "可用内存：" + num);
        return num + "%";
    }

    public static List<File> getListTime(String fileName) {
        List<File> fileList = new ArrayList<>();
        String imagePath = Environment.getExternalStorageDirectory().getPath() + "/aosen/adv/" + fileName;
        File file = new File(imagePath);
        if (!file.exists()) {
            file.mkdirs();
        }
        File[] files = file.listFiles();
        if (files.length > 0) {
            fileList = Arrays.asList(files);
            Collections.sort(fileList, new Comparator<File>() {
                @Override
                public int compare(File file1, File file2) {
                    if (file1.lastModified() < file2.lastModified()) {
                        return -1;
                    } else {
                        return 0;
                    }
                }
            });
        }
        return fileList;
    }

    /**
     * 删除旧的App
     */
    public static void deleteOldApp() {
        try {
            String path = Environment.getExternalStorageDirectory().getPath() + "/aosen/app";
            File file = new File(path);
            if (file.exists() && file.isDirectory()) {
                if (null != file.listFiles()) {
                    if (file.listFiles().length > 0) {
                        for (File f : file.listFiles()) {
                            if (f.isFile()) {
                                f.delete();
                            }
                        }
                    }
                }
            } else {
                file.mkdirs();
            }
        } catch (Exception e) {

        }
    }

    /**
     * 删除文件
     */
    public static void deleteFiles(String path) {
        try {
            File file = new File(path);
            if (file.exists() && file.isDirectory()) {
                if (null != file.listFiles()) {
                    if (file.listFiles().length > 0) {
                        for (File f : file.listFiles()) {
                            if (f.isFile()) {
                                f.delete();
                            }
                        }
                    }
                }
            } else {
                file.mkdirs();
            }
        } catch (Exception e) {

        }
    }

    /**
     * 删除旧的App
     */
    public static void testDeleteAdv(String name) {
        try {
            String path = Environment.getExternalStorageDirectory().getPath() + "/aosen/adv/" + name;
            File file = new File(path);
            if (file.exists() && file.isDirectory()) {
                if (null != file.listFiles()) {
                    if (file.listFiles().length > 0) {
                        for (File f : file.listFiles()) {
                            if (f.isFile()) {
                                f.delete();
                            }
                        }
                    }
                }
            } else {
                file.mkdirs();
            }
        } catch (Exception e) {

        }
    }

    /**
     * 删除旧的App
     */
    public static void deleteLic() {
        try {
            String path = Environment.getExternalStorageDirectory().getPath() + "/aosen/mipsLic";
            File file = new File(path);
            if (file.exists() && file.isDirectory()) {
                if (null != file.listFiles()) {
                    if (file.listFiles().length > 0) {
                        for (File f : file.listFiles()) {
                            if (f.isFile()) {
                                f.delete();
                            }
                        }
                    }
                }
            } else {
                file.mkdirs();
            }
        } catch (Exception e) {

        }
    }

    private static boolean returnResult(int value) {
        // 代表成功
        if (value == 0) {
            return true;
        } else if (value == 1) { // 失败
            return false;
        } else { // 未知情况
            return false;
        }
    }

    /**
     * 保存位图到本地
     *
     * @param bitmap
     * @param path   本地路径
     * @return void
     */
    public static void savaImage(Bitmap bitmap, String path) {
        File file = new File(path);
        FileOutputStream fileOutputStream = null;
        //文件夹不存在，则创建它
        if (!file.exists()) {
            file.mkdir();
        }
        try {
            fileOutputStream = new FileOutputStream(path + "/" + System.currentTimeMillis() + ".png");
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fileOutputStream);
            fileOutputStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static boolean checkVersion(String localVersion, String newVersion) {
        if (null != localVersion && !"".equals(localVersion) && null != newVersion && !"".equals(newVersion)) {
            int intLocal = Integer.parseInt(localVersion.replaceAll("\\.", ""));
            int intNew = Integer.parseInt(newVersion.replaceAll("\\.", ""));
            if (intLocal < intNew) {
                return true;
            } else {
                return false;
            }
        }
        return false;
    }

    /**
     * 获取sim卡号。失败返回null
     *
     * @param context
     * @return
     */
    @SuppressLint("MissingPermission")
    public static String getNetCode(Context context) {
        try {
            TelephonyManager tm = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);
            if (null != tm.getSimSerialNumber()) {
                return tm.getSimSerialNumber();
            } else {
                return "No netCode";
            }

        } catch (Throwable throwable) {
            return "No netCode";
        }
    }

    /**
     * 初始化设备编号--从设备中读取
     *
     * @return
     */
    public static FormBody.Builder getOkHttpFormBodyBuilder(Context context) {
        FormBody.Builder formBody = new FormBody.Builder();
        formBody.add(CommonUtils.MAC, getLocalMacAddress(context));
        String netCode = getNetCode(context);
        if (null != netCode && !"".equals(netCode)) {
            formBody.add(CommonUtils.NET_CODE, getNetCode(context));
        }
        formBody.add(CommonUtils.EQUIPMENT_CODE, Tools.initEquipmentCode());
        return formBody;
    }

    public static String initSerialNo() {
        String serial = null;

        try {

            Class<?> c = Class.forName("android.os.SystemProperties");

            Method get = c.getMethod("get", String.class);

            serial = (String) get.invoke(c, "ro.serialno");

        } catch (Exception e) {

            e.printStackTrace();

        }

        return serial;
    }

    /**
     * 初始化设备编号--从设备文本中读取
     *
     * @return
     */


    public static String initEquipmentCode() {
        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + CommonUtils.SN_FILE_PATH;

        if(new File(path).exists()){//兼容以前读取SN文件获取设备编码的就方案（旧apk升级到双apk）
            //创建读取文件的缓冲流
            try {
                Reader reader = new InputStreamReader(new FileInputStream(path));
                BufferedReader buffer = new BufferedReader(reader);
                //读取设备编号(SN)
                String equipmentCode = buffer.readLine().trim();
                LOG.i("EquipmentInfo.initEquipmentCode", "初始化SN" + equipmentCode);
                return equipmentCode;
            } catch (Throwable e) {
                LOG.e("EquipmentInfo.initEquipmentCode", e);
            }
        }else{
            String serial = "";
            //创建读取文件的缓冲流
            try {
                Class<?> c = Class.forName("android.os.SystemProperties");

                Method get = c.getMethod("get", String.class);

                serial = (String) get.invoke(c, "ro.serialno");
                LOG.i("EquipmentInfo.initEquipmentCode", "初始化SN" + serial);
                return serial;
            } catch (Throwable e) {
                LOG.e("EquipmentInfo.initEquipmentCode", e);
            }
        }
        return "";
    }

    public static MultipartBody.Builder getOkHttpMultipartBody(Context context) {
        MultipartBody.Builder builder = new MultipartBody.Builder()
                .setType(MultipartBody.FORM)
                .addFormDataPart(CommonUtils.MAC, getLocalMacAddress(context))
                .addFormDataPart(CommonUtils.NET_CODE, getNetCode(context))
                .addFormDataPart(CommonUtils.EQUIPMENT_CODE, Tools.initEquipmentCode());
        return builder;
    }

    /**
     * 检查时间是否正确
     *
     * @param val
     * @return
     */
    public static boolean checkTime(String val) {
        if (null == val || "".equals(val))
            return false;
        SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss");
        try {
            sdf.parse(val);
        } catch (ParseException e) {
            return false;
        }
        return true;
    }

    /**
     * 查找--不会查找今天的日志文件
     *
     * @return
     */
    public static List<String> getLogList(Context context) {
        List<String> pathList = new ArrayList<>();
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
            String today = sdf.format(new Date());
            String path = CommonUtils.BASE_FILEPAHT + CommonUtils.LOG_PATH;
            File f = new File(path).getParentFile();
            //查找父目录下的所有子目录下的所有日志文件
            File[] files = f.listFiles();
            if (null != files && files.length > 0) {
                for (File file : f.listFiles()) {
                    if (file.isDirectory()) {
                        for (File log : file.listFiles()) {
                            if (log.isFile()) {
                                String p = log.getName();
                                String type = p.substring(p.lastIndexOf("."), p.length());
                                if (LOG.SUFFIX.equals(type) && !p.startsWith(today)) {
                                    pathList.add(log.getAbsolutePath());
                                }
                            }
                        }
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return pathList;
    }

    /**
     * 查找
     *
     * @return
     */
    public static List<String> getAllLogList(Context context) {
        List<String> pathList = new ArrayList<>();
        try {
            String path = CommonUtils.BASE_FILEPAHT + CommonUtils.LOG_PATH;
//            String path = EquipmentInfo.getRoot() + Config.getConfig(context, Config.LOG_PATH);
            File f = new File(path).getParentFile();
            //查找父目录下的旧版本日志文件
            for (File file : f.listFiles()) {
                if (file.isDirectory())
                    continue;
                String p = file.getName();
                String type = p.substring(p.lastIndexOf("."), p.length());
                if (LOG.SUFFIX.equals(type)) {
                    //文件重命名
                    String s = p.substring(0, p.indexOf("_") + 1) + "old" + LOG.SUFFIX;
                    File newFile = new File(file.getParentFile(), s);
                    file.renameTo(newFile);
                    pathList.add(newFile.getAbsolutePath());
                }
            }
            //查找父目录下的所有子目录下的所有日志文件
            f = new File(path);
            for (File file : f.listFiles()) {
                if (!file.isDirectory()) {
                    if (file.isFile()) {
                        String p = file.getName();
                        String type = p.substring(p.lastIndexOf("."), p.length());
                        if (LOG.SUFFIX.equals(type)) {
                            pathList.add(file.getAbsolutePath());
                        }
                    }
                }
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return pathList;
    }

    /**
     * 判断设备当前网络是否可用
     *
     * @param context
     * @return
     */
    public static boolean isNetworkConnected(Context context) {
        if (context != null) {
            ConnectivityManager mConnectivityManager = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo mNetworkInfo = mConnectivityManager.getActiveNetworkInfo();
            if (mNetworkInfo != null) {
                System.out.println("网络类型:" + mNetworkInfo.getType());
                return mNetworkInfo.isAvailable();
            }
        }
        return false;
    }

    /**
     * 判断服务是否开启
     *
     * @return
     */
    public static boolean isServiceRunning(Context context, String ServiceName) {
        if (("").equals(ServiceName) || ServiceName == null) {
            return false;
        }
        ActivityManager myManager = (ActivityManager) context
                .getSystemService(Context.ACTIVITY_SERVICE);
        ArrayList<ActivityManager.RunningServiceInfo> runningService = (ArrayList<ActivityManager.RunningServiceInfo>) myManager
                .getRunningServices(30);
        for (int i = 0; i < runningService.size(); i++) {
            if (runningService.get(i).service.getClassName().toString()
                    .equals(ServiceName)) {
                return true;
            }
        }
        return false;
    }

    /**
     * 获取应用版本号
     *
     * @param context
     * @return
     */
    public static String getAppVersion(Context context) {
        String versionName;
        try {
            versionName = context
                    .getPackageManager()
                    .getPackageInfo(context.getPackageName(), 0)
                    .versionName;

            if ("yibeimoudle".equals(BuildConfig.TARGET_CUSTOMER)) {
                return versionName+"-aar";
            } else {
                return versionName;
            }
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
            return "1.0.1";
        }
    }

    /**
     * 将pathList 的文件进行压缩。并删除旧文件，返回新的压缩文件的路劲
     *
     * @param pathList
     * @return 返回新的压缩文件的路劲List
     * @throws IOException
     */
    public static List<String> zip(List<String> pathList) {
        List<String> zipPaths = new ArrayList();
        try {
            for (int i = 0; i < pathList.size(); i++) {
                String path = pathList.get(i);
                //压缩文件
                String zipPath = path.substring(0, path.lastIndexOf(".")) + ".zip";
                FileOutputStream os = new FileOutputStream(zipPath);
                //压缩
                ZipUtils.toZip(new File(path), os);
                os.flush();
                new File(path).delete();
                zipPaths.add(zipPath);
            }
        } catch (Throwable e) {
            e.printStackTrace();
        }
        return zipPaths;
    }


    public static Date getNetTime() {
        try {
            URL url = new URL("http://129.204.64.118:88");
            URLConnection uc = url.openConnection();//生成连接对象
            uc.connect(); //发出连接
            long ld = uc.getDate(); //取得网站日期时间
//            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(ld);
            return calendar.getTime();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static String getIP() {
        StringBuilder IPStringBuilder = new StringBuilder();
        try {
            Enumeration<NetworkInterface> networkInterfaceEnumeration = NetworkInterface.getNetworkInterfaces();
            while (networkInterfaceEnumeration.hasMoreElements()) {
                NetworkInterface networkInterface = networkInterfaceEnumeration.nextElement();
                Enumeration<InetAddress> inetAddressEnumeration = networkInterface.getInetAddresses();
                while (inetAddressEnumeration.hasMoreElements()) {
                    InetAddress inetAddress = inetAddressEnumeration.nextElement();
                    if (!inetAddress.isLoopbackAddress() &&
                            !inetAddress.isLinkLocalAddress() &&
                            inetAddress.isSiteLocalAddress()) {
                        IPStringBuilder.append(inetAddress.getHostAddress().toString() + "\n");
                    }
                }
            }
        } catch (SocketException ex) {

        }

        String IP = IPStringBuilder.toString();
        return IP;
    }

    /**
     * 获取随机时间值
     *
     * @param min
     * @param max
     * @param scl
     * @return
     */
    public static long getRandomNum(int min, int max, int scl) {
        int pow = (int) Math.pow(10, scl);//指定小数位
        double one = Math.floor((Math.random() * (max - min) + min) * pow) / pow;
        long time = (long) (one * 1000);
        return time;
    }

    public static void silentInstall(String apkAbsolutePath, Context context) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        File file = new File(apkAbsolutePath);

        Uri uri = FileProvider.getUriForFile(context,
                "com.ostms.adv.provider",
                file);
        intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(
                uri, "application/vnd.android.package-archive");
        context.startActivity(intent);
    }

    public static void setLogCatFile(String filePath) {
        String path = CommonUtils.BASE_FILEPAHT + filePath;
        File file = new File(path);
        if (!file.exists()) {
            file.mkdirs();
        }
    }

    /**
     * 设备重启
     *
     * @param context
     */
    public static void reboot(Context context) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        pm.reboot("");
    }

    public static String getLocalMacAddress(Context context) {
        String mac;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            mac = getMachineHardwareAddress();
        } else {
            WifiManager wifi = (WifiManager) context
                    .getSystemService(Context.WIFI_SERVICE);
            WifiInfo info = wifi.getConnectionInfo();
            mac = info.getMacAddress();
        }

        return mac;
    }

    /**
     * 获取设备的mac地址和IP地址
     *
     * @return
     */
    public static String getMachineHardwareAddress() {
        Enumeration<NetworkInterface> interfaces = null;
        try {
            interfaces = NetworkInterface.getNetworkInterfaces();
        } catch (SocketException e) {
            e.printStackTrace();
        }
        String hardWareAddress = null;
        NetworkInterface iF = null;
        while (interfaces.hasMoreElements()) {
            iF = interfaces.nextElement();
            try {
                hardWareAddress = bytesToString(iF.getHardwareAddress());
                if (hardWareAddress == null) continue;
            } catch (SocketException e) {
                e.printStackTrace();
            }
        }
        return hardWareAddress;
    }

    /***
     * byte转为String
     * @param bytes
     * @return
     */
    private static String bytesToString(byte[] bytes) {
        if (bytes == null || bytes.length == 0) {
            return null;
        }
        StringBuilder buf = new StringBuilder();
        for (byte b : bytes) {
            buf.append(String.format("%02X:", b));
        }
        if (buf.length() > 0) {
            buf.deleteCharAt(buf.length() - 1);
        }
        return buf.toString();
    }

    /**
     * 获取内容存储中的值
     *
     * @param context
     * @param key     使用当前类中定义的常量
     * @return
     */
    public static String getProperties(Context context, String key) {
        try {
            String[] keys = key.split("\\.");
            if (keys.length == 2) {
                SharedPreferences setting = context.getSharedPreferences(keys[0], 0);
                return setting.getString(keys[1], null);
            }
        } catch (Throwable e) {
            Log.e("getProperties", "getProperties异常", e);
            return null;
        }
        return null;
    }

    /**
     * @param context
     * @param key
     * @param value
     */
    public static void setProperties(Context context, String key, String value) {
        try {
            String[] keys = key.split("\\.");
            SharedPreferences.Editor edit = context.getSharedPreferences(keys[0], 0).edit();
            edit.putString(keys[1], value);
            edit.commit();
        } catch (Throwable e) {
            Log.e("setProperties", "setProperties异常", e);
        }
    }

    /**
     * 获取设备密钥，如果密钥为null会自动注册设备
     *
     * @param context
     * @return
     */
    public static String getEquipmentKey(Context context) {
        return Tools.getProperties(context, CommonUtils.EQUIPMENT_KEY);
    }

    /**
     * 检查是否注册，
     *
     * @param context
     */
    public static boolean checkRegister(Context context) {
        String equipmentKey = getEquipmentKey(context);
        if (equipmentKey == null) {
            return false;
        }
        return true;
    }

    private static Bitmap addLogo(Bitmap src, Bitmap logo) {
        if (src == null) {
            return null;
        }

        if (logo == null) {
            return src;
        }

        //获取图片的宽高
        int srcWidth = src.getWidth();
        int srcHeight = src.getHeight();
        int logoWidth = logo.getWidth();
        int logoHeight = logo.getHeight();

        if (srcWidth == 0 || srcHeight == 0) {
            return null;
        }

        if (logoWidth == 0 || logoHeight == 0) {
            return src;
        }

        //logo大小为二维码整体大小的1/5
        float scaleFactor = srcWidth * 1.0f / 5 / logoWidth;
        Bitmap bitmap = Bitmap.createBitmap(srcWidth, srcHeight, Bitmap.Config.ARGB_8888);
        try {
            Canvas canvas = new Canvas(bitmap);
            canvas.drawBitmap(src, 0, 0, null);
            canvas.scale(scaleFactor, scaleFactor, srcWidth / 2, srcHeight / 2);
            canvas.drawBitmap(logo, (srcWidth - logoWidth) / 2, (srcHeight - logoHeight) / 2, null);

            canvas.save();
            canvas.restore();
        } catch (Exception e) {
            bitmap = null;
            e.getStackTrace();
        }

        return bitmap;
    }

    public static void setNetTime() {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    URL url = new URL("http://129.204.64.118:88");
//                    URL url = new URL("https://www.baidu.com");
                    URLConnection uc = url.openConnection();
                    uc.connect();
                    long ld = uc.getDate(); //取得网站日期时间
                    //SystemClock.setCurrentTimeMillis(ld);
                    Calendar calendar = Calendar.getInstance();
                    calendar.setTimeInMillis(ld);
                    LOG.i(TAG, "服务器时间：" + calendar.getTime().toString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 获取待机广告
     */
    public static String getAdvStandby(Context context) {
        String json = Tools.getProperties(context, CommonUtils.ADV_STANDBY);
        return json;
    }

    /**
     * 获取默认广告
     */
    public static String getDefaultAdv(Context context) {
        String json = Tools.getProperties(context, CommonUtils.ADV_DEFAULTADV);
        return json;
    }

    public static String getSystemProp(String systemField, String defVal) {
        try {
            Class cls = Class.forName("android.os.SystemProperties");
            Method method = cls.getMethod("get", String.class, String.class);
            method.setAccessible(true);
            return (String) method.invoke(null, systemField, defVal);
        } catch (
                Exception e) {
            e.printStackTrace();
        }
        return "";
    }
}
